package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.constants.PlatformConst;
import com.authine.cloudpivot.ext.dto.JobDto;
import com.authine.cloudpivot.ext.dto.voucher.Voucher;
import com.authine.cloudpivot.ext.enums.system.TriggerMetaStatusEnum;
import com.authine.cloudpivot.ext.service.VoucherService;
import com.authine.cloudpivot.ext.service.voucher.impl.RecordingVoucherPmServiceImpl;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @Author: liwei
 * @DateTime: 2021/10/26
 * @Description: TODO 金蝶生成凭证任务执行器
 */
@Path("KingDeeJobController")
@Slf4j
public class KingDeeJobController extends ApplicationService {

    private VoucherService voucherService = new VoucherService();


    @Path("handleVoucher")
    @POST
    @Operation(summary = "凭证处理任务", tags = CUSTOM_SERVICE)
    public void handleVoucher(@Parameter JobDto jobDto){

        Assert.notNull(jobDto,"凭证处理任务入参不能为空");
        // 设置token认证信息
        RequestContext.get().setCorpLoginId(PlatformConst.corpLoginId);
        RequestContext.get().setLoginId(PlatformConst.loginId);
        RequestContext.get().setLoginName(PlatformConst.loginName);

        log.info("========================================定时任务获取凭证列表 <<<<<开始>>>>> jobDto：{}",jobDto);

        //  根据日期分组 获取每日凭证
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_WEEK, calendar.get(Calendar.DAY_OF_WEEK) - 1);
        date = calendar.getTime();
        String accDate = format.format(date);

        try{
            SingleResponse<List<Voucher>> response = voucherService.listVoucher(accDate);
            log.info("定时任务获取凭证列表 response：{}",response);

            Assert.isTrue(response.isSuccess(),"定时任务获取凭证列表失败");
            List<Voucher> data = response.getData();

            if(!CollectionUtils.isEmpty(data)){
                Map<String, List<Voucher>> groupByAccountName = data.stream().collect(Collectors.groupingBy(Voucher::getAccount_name));
                log.info("定时任务获取凭证列表 分组之后数据打印 groupByAccountName:{}",groupByAccountName);

                groupByAccountName.forEach((k, v) -> {
                    SingleResponse<Integer> integerSingleResponse = voucherService.pushVoucher(v);
                    log.info("金蝶汇总凭证--数量：{}，时间：{}",integerSingleResponse.getData(),v.get(0).getCreatedTime().toString());
                });
            }else {
                log.info("定时任务获取凭证列表 数据库未找到符合条件数据 >>>");
            }

        }catch (Exception e){
            // 修改任务触发器状态为已 失败
            Map<String,Object> triggerMetaMap = Maps.newHashMap();
            triggerMetaMap.put("id", jobDto.getTriggerMetaId());
            triggerMetaMap.put("trigger_status", TriggerMetaStatusEnum.FAILED.id);
            BoServiceUtils.updateMainBo(ModelConst.T_TRIGGER_META_FINA, triggerMetaMap);

            log.info("========================================定时任务获取凭证列表 <<<<<异常>>>>> exception:{}",e);
        }
        log.info("========================================定时任务获取凭证列表 <<<<<结束>>>>>");
        // 修改任务触发器状态为已执行
        Map<String,Object> triggerMetaMap = Maps.newHashMap();
        triggerMetaMap.put("id", jobDto.getTriggerMetaId());
        triggerMetaMap.put("trigger_status", TriggerMetaStatusEnum.EXECUTED.id);
        BoServiceUtils.updateMainBo(ModelConst.T_TRIGGER_META_FINA, triggerMetaMap);
        // 清除登录信息
        RequestContext.clear();
    }

}
